package com.hzit.aop.proxy.dynamic;

import com.hzit.aop.dao.UserDao;
import com.hzit.aop.dao.impl.UserDaoImpl;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 类名：
 * 作者：WF
 * 功能：动态代理实现之CGLIB,通过继承父类实现代理
 */
public class UserDaoDynamicCGLIBImpl implements MethodInterceptor {
	private UserDao userDao;
	public UserDaoDynamicCGLIBImpl(){
		userDao = new UserDaoImpl();
	}
	//1. 创建对象对象
	public UserDaoImpl createProxyObject(){
		Enhancer enhancer = new Enhancer();
		enhancer.setCallback(this);                 // 设置回调
		enhancer.setSuperclass(UserDaoImpl.class);  // 设置父类
		return (UserDaoImpl) enhancer.create();
	}
	//2. 当通过代理对象调用目标对象的方法时自动调用
	@Override
	public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
		if(method.getName().equals("query")){
			checkSecurity();
		}
		//调用目标对象的方法
		return methodProxy.invokeSuper(o,objects);
	}

	private void checkSecurity(){
		System.out.println("CGLIB动态代理正在进行安全性检查。。。");
	}
}
